package com.yc.damai.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.yc.damai.bean.Result;
import com.yc.damai.bean.User;
import com.yc.damai.biz.BizException;
import com.yc.damai.biz.UserBiz;

@WebServlet("/login.s")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserBiz biz = new UserBiz();
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// post 请求要设置字符集
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");		
		try {
			User user = biz.login(username, password);
			request.getSession().setAttribute("loginedUser", user);
			String json = new Gson().toJson(new Result(1,"登录成功"));
			response.getWriter().append(json);
		} catch (BizException e) {
			e.printStackTrace();
			String json = new Gson().toJson(new Result(0,e.getMessage()));
			response.getWriter().append(json);
		}
	}

}

